package com.cn.jinl.service;


import com.cn.jinl.api.IOnDutyBgService;
import com.cn.jinl.dao.OnDutyBgMapper;
import com.cn.jinl.domain.OnDutyBg;
import com.cn.jinl.domain.OnDutyBgExample;
import com.cn.jinl.utils.CollectionsUtil;
import com.cn.jinl.utils.CommonUtil;
import com.cn.jinl.utils.Constants;
import com.cn.jinl.utils.QueryForm;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Map;

@EnableScheduling
@Service
public class OnDutyBgServiceImpl implements IOnDutyBgService {

    @Autowired
    private OnDutyBgMapper onDutyBgMapper;

    @Override
    public List<OnDutyBg> getOnDutyBgList(QueryForm queryForm) throws Exception {
        int count = onDutyBgMapper.selectOndutyBGListCount(queryForm);
        List<OnDutyBg> result = onDutyBgMapper.selectOndutyBGList(queryForm);
        if(CollectionsUtil.isNotEmpty(result)){
            result.get(0).setCount(count);
        }
        return result;
    }

    @Override
    public OnDutyBg getOnDutyBgById(String id) throws Exception {
        OnDutyBgExample example = new OnDutyBgExample();
        example.createCriteria().andIdEqualTo(id).andStatusEqualTo(Constants.NORMAL_STATUS);
        List<OnDutyBg> result = onDutyBgMapper.selectByExample(example);
        if(CollectionUtils.isEmpty(result)){
            return null;
        }
        return result.get(0);
    }

    @Override
    public String updateOnDutyBg(OnDutyBg onDutyBg) throws Exception {
        if(StringUtils.isEmpty(onDutyBg.getId())){
            return "id不能为空!";
        }
        OnDutyBgExample example = new OnDutyBgExample();
        example.createCriteria().andIdEqualTo(onDutyBg.getId());
        int count = onDutyBgMapper.updateByExampleSelective(onDutyBg,example);
        return CommonUtil.outStr(count);
    }


    @Scheduled(cron = "0 0/10 * * * ?")
    public void insertAutoOnDutyBgInfo(){
        Map<String,String> dutyMap = CommonUtil.getOnDutyAndWhiteDay();
        String dutyDay = dutyMap.get("dutyDay");
        OnDutyBgExample example = new OnDutyBgExample();
        example.createCriteria().andDutyDayEqualTo(dutyDay).andStatusEqualTo(Constants.NORMAL_STATUS);
        int count = onDutyBgMapper.countByExample(example);
        if(count > 0){
            return;
        }

        OnDutyBg onDutyBg = new OnDutyBg();
        onDutyBg.setId(CommonUtil.generateRandomNum("onDutyBg-"));
        onDutyBg.setDutyDay(dutyDay);
        onDutyBgMapper.insertSelective(onDutyBg);
    }
}
